<template>
  <div
    :id="id"
    :style="{
      width: width + 'rem',
      height: height + 'rem',
      margin: '0.9rem auto'
    }"
    class="m-map"
  />
</template>

<script>
export default {
  props: {
    width: {
      type: Number,
      default: 300
    },
    height: {
      type: Number,
      default: 300
    },
    point: {
      type: Array,
      default() {
        return [116.46, 39.92];
      }
    }
  },
  data() {
    return {
      id: `map`,
      key: "e793d140ef971b56ea4abc443302fe49"
    };
  },
  watch: {
    // eslint-disable-next-line no-unused-vars
    point: function(val, old) {
      this.map.setCenter(val);
      this.marker.setPosition(val);
    }
  },
  mounted() {
    // let _this = this;
    // this.map = new AMap.Map("con", {
    //   center: _this.point, // 初始化地图时显示的中心点坐标
    //   zoom: 11, // 初始化地图时显示的地图放大等级
    //   resizeEnable: true // 调整任意窗口的大小，自适应窗口
    // });
    let self = this;
    self.id = `map${Math.random()
      .toString()
      .slice(4, 6)}`;

    window.onmaploaded = () => {
      let map = new window.AMap.Map(self.id, {
        resizeEnable: true,
        zoom: 16,
        center: self.point
      });
      // self.map = map;
      window.AMap.plugin("AMap.ToolBar", () => {
        let toolbar = new window.AMap.ToolBar();
        map.addControl(toolbar);
        let marker = new window.AMap.Marker({
          icon: "https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png",
          position: self.point
        });
        self.marker = marker;
        marker.setMap(map);
      });
    };
    // http://webapi.amap.com/maps?v=1.4.4&key=e793d140ef971b56ea4abc443302fe49
    const url = ` http://webapi.amap.com/maps?v=1.4.4&key=${
      self.key
    }&callback=onmaploaded`;
    let jsapi = document.createElement("script");
    jsapi.charset = "utf-8";
    jsapi.src = url;
    document.head.appendChild(jsapi);
  }
};
</script>
